﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using RiskMan.DataClass.Models;
using RiskMan.DataClass.Models.Quik;
using RiskMan.DataClass.Models.RM;
using RiskMan.Views.Dialogs;
using System.Collections.ObjectModel;


namespace RiskMan.Views.LimitStock
{
    /// <summary>
    /// Логика взаимодействия для Window1.xaml
    /// </summary>
    public partial class newLimitStock : Window
    {
        public ModuleLimitStockModel ModuleLimit;
        private MainWindow mainWindow;
        private DataClass.Data data;
        ObservableCollection<Limits> coll = new ObservableCollection<Limits>();
        List<Trade> trades;

        ObservableCollection<string> tmpSeccodeList = new ObservableCollection<string>();

        public newLimitStock(MainWindow mainWindow, ModuleLimitStockModel moduleLimitListModel, DataClass.Data data, bool isEdit)
        {
            InitializeComponent();

            this.mainWindow = mainWindow;
            this.ModuleLimit = moduleLimitListModel;
            this.data = data;
            trades = data.GetTradeList();

            List<String> seccode = data.GetSeccodeList();

            #region ClientCode

            var result = new List<Trade>();

            for (int j = 0; j < trades.Count; j++)
            {
                bool tr = false;

                for (int i = 0; i < data.LimitStockList.Count; i++)
                {
                    if (trades[j].Account == data.LimitStockList[i].Account && trades[j].ClientCode == data.LimitStockList[i].ClientCode)
                    {
                        tr = true;
                    }
                }

                if (tr == false)
                    result.Add(trades[j]);
            }
            trades = result;

            if (isEdit == true)
                trades.Add(new Trade() { Account = moduleLimitListModel.Account, ClientCode = moduleLimitListModel.ClientCode });

            cmbxSelectAccount.ItemsSource = trades.Select(a => a.ClientCode).ToList();
            if (cmbxSelectAccount.Items.Count > 0)
                cmbxSelectAccount.SelectedIndex = 0;

            //cmbxSelectAccount.ItemsSource = trades.Select(a => a.ClientCode + "_" + a.Account);
            //for (int i = 0; i < cmbxSelectAccount.Items.Count; i++)
            //{
            //    if (cmbxSelectAccount.Items[i].ToString() ==
            //        limitListModel.ClientCode + "_" + limitListModel.Account)
            //        cmbxSelectAccount.SelectedIndex = i;
            //}

            #endregion

            #region Seccode

            cmbxSelectInstrument.ItemsSource = data.GetSeccodeList();
            for (int i = 0; i < cmbxSelectInstrument.Items.Count; i++)
            {
                tmpSeccodeList.Add(cmbxSelectInstrument.Items[i].ToString());
                if (cmbxSelectInstrument.Items[i].ToString() == moduleLimitListModel.Seccode)
                    cmbxSelectInstrument.SelectedIndex = i;
            }
            #endregion
            string[] listItems = { "Лонг/Шорт", "Шорт", "Лонг" };
            cmbxRegim.ItemsSource = listItems;
            chbxIsAllowClose.IsChecked = false;
        }

        public newLimitStock(ObservableCollection<Limits> tmpColl, MainWindow mainWindow, ModuleLimitStockModel moduleLimitListModel, DataClass.Data data, bool isEdit)
        {
            InitializeComponent();

            this.mainWindow = mainWindow;
            this.ModuleLimit = moduleLimitListModel;

            this.data = data;
            trades = data.GetTradeList();

            List<String> seccode = data.GetSeccodeList();

            #region ClientCode

            var result = new List<Trade>();

            for (int j = 0; j < trades.Count; j++)
            {
                bool tr = false;

                for (int i = 0; i < data.LimitStockList.Count; i++)
                {
                    if (trades[j].Account == data.LimitStockList[i].Account && trades[j].ClientCode == data.LimitStockList[i].ClientCode)
                    {
                        tr = true;
                    }
                }

                if (tr == false)
                    result.Add(trades[j]);
            }
            trades = result;

            if (isEdit == true)
            {
                trades.Add(new Trade() { Account = moduleLimitListModel.Account, ClientCode = moduleLimitListModel.ClientCode });
                cmbxSelectAccount.ItemsSource = trades.Select(a => a.ClientCode).ToList();
                cmbxSelectAccount.SelectedValue = ModuleLimit.ClientCode;
            }
            else
            {
                cmbxSelectAccount.ItemsSource = trades.Select(a => a.ClientCode).ToList();
                cmbxSelectAccount.SelectedIndex = 0;
            }

            #endregion

            #region Seccode

            cmbxSelectInstrument.ItemsSource = data.GetSeccodeList();
            for (int i = 0; i < cmbxSelectInstrument.Items.Count; i++)
            {
                tmpSeccodeList.Add(cmbxSelectInstrument.Items[i].ToString());
                //if (cmbxSelectInstrument.Items[i].ToString() == limitListModel.Seccode)
                //    cmbxSelectInstrument.SelectedIndex = i;
            }

            for (int i = 0; i < tmpSeccodeList.Count; i++)
            {
                foreach (var item in tmpColl)
                {
                    if (item.instrument == tmpSeccodeList[i])
                    {
                        tmpSeccodeList.Remove(tmpSeccodeList[i]);
                        break;
                    }
                }
            }
            #endregion
            cmbxSelectInstrument.ItemsSource = tmpSeccodeList;
            coll = tmpColl;
            dtgdLimit.ItemsSource = coll;
            dtgdLimit.Items.Refresh();

            string[] listItems = { "Лонг/Шорт", "Шорт", "Лонг" };
            cmbxRegim.ItemsSource = listItems;
            cmbxRegim.SelectedItem = "Лонг/Шорт";
            chbxIsAllowClose.IsChecked = Convert.ToBoolean(ModuleLimit.IsAllowClose);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void btnAddRow_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(cmbxSelectInstrument.Text.Trim()) && txbxLimitQuantity.Text.Trim() != String.Empty && !string.IsNullOrEmpty(cmbxRegim.Text.Trim()))
            {
                coll.Add(new Limits() { instrument = cmbxSelectInstrument.Text.Trim(), limit = txbxLimitQuantity.Text.Trim(), regim = cmbxRegim.Text });
                dtgdLimit.ItemsSource = coll;
                dtgdLimit.Items.Refresh();

                for (int i = 0; i < tmpSeccodeList.Count; i++)
                {
                    foreach (var item in coll)
                    {
                        if (item.instrument == tmpSeccodeList[i])
                        {
                            tmpSeccodeList.Remove(tmpSeccodeList[i]);
                            break;
                        }
                    }
                }
                cmbxSelectInstrument.ItemsSource = tmpSeccodeList;

            }
            else
                new DialogMessage("Проверьте правильность заполнения полей", "Предупреждение");
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            ModuleLimitStockModel ModuleLimit;
            if (coll.Count > 0)
            {
                foreach (var item in coll)
                {
                    if (cmbxSelectAccount.SelectedIndex >= 0)
                    {
                        ModuleLimit = new ModuleLimitStockModel();
                        ModuleLimit.ClientCode = cmbxSelectAccount.SelectedValue.ToString();
                        List<Trade> trades = data.GetTradeList();

                        for (int i = 0; i < trades.Count; i++)
                            if (trades[i].ClientCode == ModuleLimit.ClientCode)
                                ModuleLimit.Account = trades[i].Account;
                    }
                    else
                    {
                        new DialogOkCancel("Выберите код клиента(счет)!", "Ошибка добавления");
                        return;
                    }


                    if (!string.IsNullOrEmpty(item.instrument))
                    //item.instrument != String.Empty && item.instrument !=null)
                    {
                        bool tmpBool = false;
                        ModuleLimit.Regim = item.regim;
                        ModuleLimit.Seccode = item.instrument;
                        ModuleLimit.LimitStock = Convert.ToInt32(item.limit);
                        ModuleLimit.IsAllowClose = Convert.ToBoolean(chbxIsAllowClose.IsChecked);

                        foreach (var tmpItem in mainWindow._dataProvider.LimitStockList)
                        {
                            if (tmpItem.Seccode == ModuleLimit.Seccode && tmpItem.ClientCode == ModuleLimit.ClientCode)
                            {
                                tmpBool = true;
                                if (tmpItem.LimitStock != ModuleLimit.LimitStock)
                                {
                                    tmpItem.LimitStock = ModuleLimit.LimitStock;
                                }
                                if (tmpItem.Regim != ModuleLimit.Regim)
                                {
                                    tmpItem.Regim = ModuleLimit.Regim;
                                }
                                if (tmpItem.IsAllowClose != ModuleLimit.IsAllowClose)
                                {
                                    tmpItem.IsAllowClose = ModuleLimit.IsAllowClose;
                                }
                            }
                        }
                        if (tmpBool == false)
                            mainWindow._dataProvider.LimitStockList.Add(ModuleLimit);
                    }
                }

                int countLimit = mainWindow._dataProvider.LimitStockList.Count;
                for (int i = 0; i < countLimit; i++)
                    foreach (var item in mainWindow._dataProvider.LimitStockList)
                    {
                        if (item.ClientCode == cmbxSelectAccount.SelectedValue.ToString())
                        {
                            bool result = false;
                            foreach (var itemColl in coll)
                            {
                                if (item.Seccode == itemColl.instrument)
                                    result = true;
                            }
                            if (result == false)
                            {
                                mainWindow._dataProvider.LimitStockList.Remove(item);
                                break;
                            }
                        }

                    }

                this.DialogResult = true;
            }
            this.Close();
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if (coll.Count > 0 && dtgdLimit.SelectedCells.Count > 0)
            {
                foreach (var item in coll)
                    if (item.Equals(dtgdLimit.SelectedItems[0]))
                    {
                        if (item.instrument != null && item.instrument != String.Empty)
                            tmpSeccodeList.Add(item.instrument.ToString());

                        coll.Remove(item);
                        break;
                    }
                cmbxSelectInstrument.ItemsSource = tmpSeccodeList;
            }
        }


    }

    public class Limits
    {
        public string instrument { get; set; }
        public string limit { get; set; }
        public string regim { get; set; }


    }

    public class RegimList : List<string>
    {
        public RegimList()
        {
            this.Add("Лонг/Шорт");
            this.Add("Шорт");
            this.Add("Лонг");
        }
    }
}
